package com.digua.base.base

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.digua.base.util.CollUtil

open class ViewPager2Adapter : FragmentStateAdapter {
    var fragments: ArrayList<Fragment>
    private var fragmentManager: FragmentManager

    constructor(activity: FragmentActivity, fragments: ArrayList<Fragment>) : super(activity) {
        this.fragments = fragments
        this.fragmentManager = activity.supportFragmentManager
    }

    constructor(fragmentManager: FragmentManager, lifecycle: Lifecycle, fragments: ArrayList<Fragment>) : super(fragmentManager, lifecycle) {
        this.fragments = fragments
        this.fragmentManager = fragmentManager
    }

    override fun getItemCount() = CollUtil.size(fragments)

    override fun createFragment(position: Int) = fragments[position]

    override fun getItemId(position: Int) =  createFragment(position).hashCode().toLong()

    override fun containsItem(itemId: Long): Boolean {
        for (i in 0 until fragments.size) {
            if (getItemId(i) == itemId) return true
        }
        return false
    }
}